// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Globalization;
using System.Text;

namespace SnapObjects.Data.Sqlite
{
    internal class SqliteUpdateSqlGenerator : UpdateSqlGenerator
    {
        public SqliteUpdateSqlGenerator(SqliteSqlGenerationHelper SqliteSqlGenerationHelper) :
            base(SqliteSqlGenerationHelper)
        {
        }

        protected override ResultSetMapping AppendSelectAffectedCountSql(StringBuilder sqlStringBuilder, string name, string schema, int sqlPosition)
        {
            sqlStringBuilder
                .Append("SELECT changes()")
                .AppendLine(this.SqlGenerationHelper.StatementTerminator)
                .AppendLine();

            return ResultSetMapping.RowCountAndLastInResultSet;
        }

        protected override void AppendIdentityWhereCondition(StringBuilder sqlStringBuilder, ColumnModification columnModification)
        {
            this.SqlGenerationHelper.DelimitIdentifier(sqlStringBuilder, columnModification.MappedColumn);
            sqlStringBuilder.Append(" = ")
                .Append("last_insert_rowid()");

        }

        protected override void AppendRowsAffectedWhereCondition(StringBuilder sqlStringBuilder, int expectedRowsAffected)
        {
            sqlStringBuilder
                           .Append("changes() = ")
                           .Append(expectedRowsAffected.ToString(CultureInfo.InvariantCulture));
        }

        public override string GenerateNextSequenceValueSql(string name, string schema)
        {
            throw new NotSupportedException(SqliteStrings.SequencesNotSupported);
        }
    }
}
